package controllers.tutor;

import controllers.admin.permission.AuthorityController;
import controllers.deadbolt.Deadbolt;
import controllers.modules.cas.SecureCAS;
import models.batchlist.TutorBatch;
import models.permission.User;
import models.tutor.ThemeList;
import models.tutor.Tutor;
import play.Logger;
import play.db.jpa.JPA;
import play.modules.router.Get;
import play.modules.router.Post;
import play.mvc.Util;
import play.mvc.With;
import services.tutor.TutorService;
import utils.JSON;
import utils.R;

import javax.persistence.EntityManager;
import javax.persistence.FlushModeType;
import java.util.Date;

/**
 * 导师信息维护 Controller
 * Created by FireFire on 6/26 0026.
 */
public class Tutors extends AuthorityController {


    @Util
    public static Tutor currentTutor(){
        User currentUser = currentUser();
        Tutor tutor = TutorService.currentUserRelatedTutor(currentUser);
        return tutor;
    }
    /**
     * 得到当前的导师信息，将导师的信息封装为JSON数据传递到前台页面。
     *
     */
    @Get("/tts/tutor/index")
    public static void index(){
        User currentUser = currentUser();
        if(currentUser==null)
            error("非导师用户，无法访问！");
        Tutor tutor = TutorService.currentUserRelatedTutor(currentUser);

        Logger.info("hello world , %s",currentUser);

        render(tutor);
    }

    /**
     * 保存或更新item
     * @param item
     */
    @Post("/tts/tutor/theme-list/save")
    public static void saveThemeList(ThemeList item){
        try{
            item.tutor = currentTutor();

            User currentUser = currentUser();
            item.lastUpdateDate = new Date();
            item.lastUpdater = currentUser.userName;
            item.save();
            R r = R.ok();
            renderJSON(r);
        }catch(Exception e) {
            error(e.getMessage());
        }
    }


    /**
     * type=0; rank = 0 ;
     * type=1; visible = 0;
     * type=2; visible = 1;
     */
    @Post("/tts/tutor/batchUpdate")
    public static void batchUpdate(int type,int[] ids){
        for(int i=0;i<ids.length;i++){
            ThemeList item = ThemeList.findById(new Long(ids[i]));
            if(item!=null){
                if(type==0){
                    item.rank = 0;
                }else if(type==1){
                    item.isOpen = false;
                }else if(type==2){
                    item.isOpen = true;
                }
            }
            item.save();
        }
        R r = R.ok();
        renderJSON(r);
    }


    /**
     * 变更可见性
     * @param id
     */
    @Post("/tts/tutor/toggle")
    public static void toggle(long id) {
        Tutor tutor = Tutor.findById(id);
        if(tutor!=null){
            tutor.isOpen = !tutor.isOpen;
            tutor.save();
        }
    }

    @Get("/tts/tutor/current")
    public static void info(){
        User currentUser = currentUser();
        Tutor tutor = TutorService.currentUserRelatedTutor(currentUser);
    }

}
